package com.zjshell.pricing.system.controller;



import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.validation.constraints.NotBlank;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.zjshell.pricing.common.annotation.ControllerEndpoint;
import com.zjshell.pricing.common.controller.BaseController;
import com.zjshell.pricing.common.entity.FebsResponse;



/**
 * 
 * 类名称:UploadController
 * 类描述:  
 * 创建人:杨磊   
 * 修改人:XXX 
 * 修改时间:2020年2月5日 下午8:40:46
 * 修改备注:  
 * @version 1.0.0
 * Copyright(c)2020浙江壳牌-版权所有
 */
@Slf4j
@RestController
@RequestMapping("uploadFile")
public class UploadController extends BaseController{

	 @PostMapping("file/{folder}")
	 @RequiresPermissions("uploadFile:file")
	 @ControllerEndpoint(exceptionMessage = "上传图片失败")
	 public FebsResponse uploadImg(@NotBlank(message = "{required}") @PathVariable String folder,MultipartFile file) throws IOException {
		 String contentType = file.getContentType();    // 获取文件的类型
	     System.out.println("文件类型为：" + contentType);
	     String originalFilename = getFileName(file.getOriginalFilename(),folder);     // 获取文件的原始名称
	     ApplicationHome h = new ApplicationHome(getClass());
	     File jarF = h.getSource();
	     System.out.println(jarF.getParentFile().toString());
	     String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
	     String fileUrl = path + "/static/uploadfile/"+folder + "/" + originalFilename;
	     String filePath = "/uploadfile/"+folder + "/" + originalFilename;
	     // 判断文件是否为空
	     if (!file.isEmpty()) {
	    	 File targetImg = new File(path,"uploadfile/"+folder);
	         // 判断文件夹是否存在
	         if (!targetImg.exists()) {
	        	 
	            targetImg.mkdirs();    //级联创建文件夹
	         }
	         try {
	                // 开始保存图片
	            FileOutputStream outputStream = new FileOutputStream(fileUrl);
	            outputStream.write(file.getBytes());
	            outputStream.flush();
	            outputStream.close();
	         } catch (IOException e) {
	            e.printStackTrace();
	         }

	     }
		 return new FebsResponse().success().data(filePath);
	 }

	 private String getFileName(String fileName,String folder) {
	        SimpleDateFormat formatter = new SimpleDateFormat("yyMM");
	        String filename = formatter.format(new Date());
	        filename = UUID.randomUUID().toString();
	        String ext = fileName;
	        ext = ext.substring(ext.lastIndexOf(".") + 1);
	        filename =  filename + "." + ext;
	        return filename;
	    }
}
